import { Outlet, useLocation, useAuth, useNavigate, useRequest } from 'ice';
import { useEffect } from 'react';
import styles from './index.module.css';
import userService from '@/services/user';
import { Message } from '@alifd/next';

export default function Layout() {
  const location = useLocation();
  const navigate = useNavigate();
  const [auth, setAuth] = useAuth();

  useEffect(() => {
    if (location.pathname.includes('/home')) {
      const token = localStorage.getItem('token');
      // 对已经登录过的用户进行身份验证
      if (token) {
        let verify = false;
        if (location.state) {
          if (location.state.from.includes('/home')) {
            verify = true;
            setAuth({ admin: true });
          }
        }
        if (!verify) {
          userService.info().then((data) => {
            if (data.data) {
              localStorage.setItem('user', JSON.stringify(data.data));
              console.log('通过验证');
              setAuth({ admin: true });
            } else {
              setAuth({ admin: false });
              navigate('/register');
            }
          });
        }
      } else {
        setAuth({ admin: false });
        navigate('/register');
        Message.success('请先登录');
      }
    }
  }, [location]);
  return (<div className={styles.app}>
    <Outlet />
  </div>);
}
